package datastructure.stak;

import java.util.Iterator;

/**
 * 单向链表带哨兵实现栈
 *
 * @author 杨 强
 * @package datastructure.stak
 * @createTime 2023-03-14 21:21
 */
public class LinkedListStack<E> implements Stack<E>, Iterable<E> {

    public static void main(String[] args) {
        LinkedListStack<Integer> stack = new LinkedListStack(5);
        stack.push(1);
        stack.push(2);
        stack.push(3);
        Iterator<Integer> iterator = stack.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }
        System.out.println("弹出了" + stack.pop());
        Iterator<Integer> iterator1 = stack.iterator();
        while (iterator1.hasNext()){
            System.out.println(iterator1.next());
        }
    }

    /**
     * 定义一个哨兵头节点
     */
    private final Node<E> head = new Node<>(null, null);
    /**
     * 容量
     */
    private final int capacity;
    /**
     * 栈元素个数
     */
    private int size;
    /**
     * 构造器
     * @param capacity 初始化栈的容量
     */
    public LinkedListStack(int capacity) {
        this.capacity = capacity;
    }

    @Override
    public boolean push(E value) {
        // 判断是否为满了
        if (isFull()){
            return false;
        }
        // 新节点指向现在的头节点
        Node<E> addNode = new Node<>(value, head.next);
        // 新的头节点指向添加的节点
        head.next=addNode;
        size++;
        return true;
    }

    @Override
    public E pop() {
        if (isEmpty()) {
            return null;
        }
        Node<E> first = head.next;
        head.next = first.next;
        size--;
        return first.value;
    }

    @Override
    public E peek() {
        if (isEmpty()) {
            return null;
        }
        return head.next.value;
    }


    @Override
    public boolean isEmpty() {
        // 哨兵节点的下一个节点为null就是空
        return this.head.next == null;
    }

    @Override
    public boolean isFull() {
        // 栈的元素个数等于零栈的容量就满了
        return this.size == this.capacity;
    }

    /**
     * 定义节点类
     */
    private static class Node<E>{
        E value;
        Node<E> next;
        public Node(E value, Node<E> next) {
            this.value = value;
            this.next = next;
        }
    }

    /**
     * 编写迭代器
     * @return
     */
    @Override
    public Iterator<E> iterator() {
        return new Iterator<E>() {
            Node<E> p = head.next;
            @Override
            public boolean hasNext() {
                return p != null;
            }
            @Override
            public E next() {
                E value = p.value;
                p = p.next;
                return value;
            }
        };
    }
}
